<template>
  <div class="updateProfile-page">
    <van-nav-bar :title="needTitleName + needObj.title" left-arrow @click-left="toProfile" />
    <van-popup :style="{'min-height': '30%', width: '90%'}" v-model="showpop">
      <div class="slideverify" v-show="isShowSlide">
        <!-- <SlideVerify ref="slideblock" @success="sendSmsCode"></SlideVerify> -->
        <div id="verifyCodeDemo">
          <p id="picyzm" style="margin:10px"></p>
          <div style="text-align:center;margin-bottom:5px;margin-right:10px;">点击图片刷新</div>
          <van-field
            autocomplete="off"
            v-model="picyzmValue"
            style="text-align:center;"
            placeholder="请输入4位验证码"
          />
          <div style="text-align: center;">
            <van-button style="margin:10px;width:65px;" size="small" @click="showpop = false">取消</van-button>
            <van-button style="margin:10px;width:65px;" size="small" type="info" @click="handleVerify()"
              >验证</van-button
            >
          </div>
        </div>
      </div>
    </van-popup>
    <!-- 重新整理为form表单  -->
    <van-form @submit="toUpdate">
      <van-field
        autocomplete="off"
        label="头像"
        v-if="needObj.key === 'avatar'"
        name="avatar"
        :rules="[{required: true, message: '头像未上传'}]"
      >
        <template #input>
          <van-uploader
            v-model="avatarList"
            :delete="(avatar = '')"
            :max-count="1"
            :after-read="afterReadAvatar"
            :preview-options="{
              closeable: true
            }"
          />
        </template>
      </van-field>

      <van-field
        autocomplete="off"
        label="收款码"
        v-if="needObj.key === 'qode'"
        name="qode"
        :rules="[{required: true, message: '收款码未上传'}]"
      >
        <template #input>
          <van-uploader
            v-model="avatarList"
            :delete="(qode = '')"
            :max-count="1"
            :after-read="afterReadAvatar"
            :preview-options="{
              closeable: true
            }"
          />
        </template>
      </van-field>

      <van-field
        autocomplete="off"
        v-model="typeValue"
        :name="needObj.key"
        :label="needObj.title"
        :placeholder="`请输入${needObj.title}`"
        :maxlength="needObj.key === 'nick_name' ? 16 : 99"
        v-if="!(needObj.key === 'avatar') && !(needObj.key === 'gender') && needObj.key !== 'mobile'"
        :rules="[{required: true, message: '未填写'}]"
      />

      <template v-if="needObj.key === 'mobile'">
        <van-field
          autocomplete="off"
          v-model="phone"
          clearable
          enter
          label="手机号"
          name="phone"
          placeholder="请输入正确的手机号码"
          maxlength="11"
          :rules="[
            {
              required: true,
              message: '请填写验证码'
            }
          ]"
        >
          <template #button>
            <van-button
              v-show="showcount"
              size="small"
              type="info"
              :disabled="!(phone && phone.length === 11)"
              @click="sendCode(3)"
              native-type="button"
              >发送验证码</van-button
            >
            <van-button v-show="!showcount" size="small" type="info" disabled @click="sendCode(3)" native-type="button"
              >{{ count }} s</van-button
            >
          </template>
        </van-field>
        <van-field
          autocomplete="off"
          clearable
          v-model="code"
          name="code"
          label="验证码"
          placeholder="请输入验证码"
          :rules="[
            {
              required: true,
              message: '请填写验证码'
            }
          ]"
        />
      </template>

      <van-field
        autocomplete="off"
        label="性别"
        v-if="needObj.key === 'gender'"
        name="gender"
        :rules="[{required: true, message: '未选择性别'}]"
      >
        <template #input>
          <van-radio-group v-model="gender" direction="horizontal">
            <van-radio name="0">女</van-radio>
            <van-radio name="1">男</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <div style="margin: 16px;">
        <van-button color="#1989fa" block round native-type="submit">确认修改</van-button>
      </div>
    </van-form>
    <van-popup round :close-on-click-overlay="false" v-model:show="showPopup" bind:close="onClose">
      <!-- <verCode ref="slideblock" @popFUNC="popFUNC"></verCode> -->
      <slide-verify
      :l="42"
      :r="10"
      :w="210"
      :h="155"
      @success="onSuccess"
      @fail="onFail"
      @refresh="onRefresh"
      slider-text="向右滑动"
    ></slide-verify>
    </van-popup>
  </div>
</template>

<script>
import {Toast} from 'vant'
import profileTypeList from '../../constants/profileTypeList'
import SlideVerify from '@/components/slideImg' //引入
import verCode from '@/components/verCode' //引入
import {GVerify} from '@/utils/gVerify.js'
import {cosUploadImg} from '@/utils/cosUpload.js'

export default {
  name: 'updateProfile',
  data() {
    return {
      showPopup: false,
      isShowSlide: false,
      showpop: false,
      showcount: true,
      count: '',
      timer: null,
      profileTypeList,
      titleName: '修改',
      // 组件需要
      avatarList: [],
      // 后端需要
      avatar: '',
      typeValue: '',
      phone: '',
      code: '',
      typeObj: {},
      gender: '',
      verifyCode: null,
      picyzmValue: ''
    }
  },
  components: {
    verCode,
    SlideVerify //注册组件
  },
  created() {
    const profileString = this.$route.params.profileString || localStorage.getItem('profileType')
    if (profileString) {
      // 若有, 则保存
      if (this.$route.params.profileString) {
        localStorage.setItem('profileType', this.$route.params.profileString)
      }
      this.profileType = localStorage.getItem('profileType')
    } else {
      this.$router.push('/profile')
      localStorage.removeItem('profileType')
    }
  },
  computed: {
    needObj() {
      let result
      if (this.profileType) {
        result = this.profileTypeList.find(item => item.key === this.profileType)
      } else {
        result = this.typeObj
      }
      return result
    },
    needTitleName() {
      let result
      if (this.profileType === 'payPassword') {
        result = '设置'
      } else {
        result = this.titleName
      }
      return result
    },
    disabledStatus() {
      if (this.phone && this.phone.length === 11) {
        return false
      } else {
        return true
      }
    }
  },
  methods: {
    //验证码
    creatGVerify() {
      //初始化验证码
      this.verifyCode = new GVerify({
        id: 'picyzm',
        type: 'blend'
      })
    },
    handleVerify() {
      var res = this.verifyCode.validate(this.picyzmValue)
      if (res) {
        this.sendSmsCode()
      } else {
        alert('验证码错误')
      }
    },
    hideSlide() {
      setTimeout(() => {
        this.isShowSlide = false
      }, 500)
    },
    sendSmsCode() {
      setTimeout(() => {
        this.showpop = false
        this.getQode()
      }, 500)
    },
    async getQode() {
      // 请求参数
      const TIME_COUNT = 60

      const params = {phone: this.phone, type: 3}
    
      const res = await this.$api.user.reqSendCode(params)

      if (res.code === 200) {
        Toast(res.data)
        if (!this.timer) {
          this.count = TIME_COUNT
          this.showcount = false

          this.timer = setInterval(() => {
            if (this.count > 0 && this.count <= TIME_COUNT) {
              this.count--
            } else {
              this.showcount = true
              clearInterval(this.timer)
              this.timer = null
            }
          }, 1000)
        }
      } else {
        Toast(res.msg)
      }
    },
    toProfile() {
      this.$router.push('/profile')
      localStorage.removeItem('profileType')
    },

    async _reqUploadPicture(picture) {
      let formData = new FormData()
      formData.append('filename', picture.file)
      const img_type = 'user_avatar'
      // const res = await this.$api.uploadImg.uploadPhotos(formData, img_type)
      // if (res.code === 200) {
      //   return res.data
      // }
      const res = await cosUploadImg(picture.file, img_type)
      if (res.code === 200) {
        return res.data
      }
    },

    afterReadAvatar(picture) {
      console.log(picture)
      picture.status = 'uploading'
      picture.message = '上传中...'
      // async/await函数的返回结果仍是promise对象, 使用.then()取得返回值
      this._reqUploadPicture(picture).then(res => {
        this.avatar = res
        if (!res) {
          Toast('图片上传失败!')
          picture.status = 'failed'
          picture.message = '上传失败'
        } else {
          picture.status = 'done'
        }
      })
    },

    sendCode(index) {
       this.getQode()
      // this.showPopup = true
    },
    popFUNC() {
      this.showPopup = false
      this.getQode()
    },
    onSuccess() {
      this.showPopup = false
      this.getQode()
    },

    _commonResult(res) {
      if (res.code == 200) {
        Toast(res.data)
        this.$router.push('/profile')
      }
    },

    async _updateInfo(params) {
      let res
      switch (this.needObj.key) {
        case 'avatar':
          res = await this.$api.user.reqUpdateAvatar(params)
          this._commonResult(res)
          break
        case 'nick_name':
          res = await this.$api.user.reqUpdateNickName(params)
          this._commonResult(res)
          break
        case 'mobile':
          res = await this.$api.user.reqUpdateMobile(params)
          this._commonResult(res)
          break
        case 'gender':
          res = await this.$api.user.reqUpdateGender(params)
          this._commonResult(res)
          break
        case 'qq_num':
          res = await this.$api.user.reqUpdateQq(params)
          this._commonResult(res)
          break
        case 'wx_num':
          res = await this.$api.user.reqUpdateWx(params)
          this._commonResult(res)
          break
        case 'email':
          res = await this.$api.user.reqUpdateEmail(params)
          this._commonResult(res)
          break
      }
    },

    // 确认修改
    toUpdate(values) {
      let params
      if (this.needObj.key === 'avatar') {
        if (!this.avatar) {
          Toast('请先上传图片！')
          return
        }
        params = {avatar: this.avatar}
      } else if (this.needObj.key === 'gender') {
        params = {[this.needObj.key]: values[this.needObj.key] * 1}
      } else if (this.needObj.key === 'mobile') {
        params = {phone: this.phone, code: this.code}
      } else {
        params = {[this.needObj.key]: values[this.needObj.key]}
      }
      this._updateInfo(params)
    }
  }
}
</script>

<style scoped></style>
